<template>
  <div>
    <el-form ref="prodFormRef" v-loading="loading" :model="prodForm" :rules="prodFormRule" label-width="80px">
      <el-tabs v-model="activeName" type="card" @tab-click="handleClickNextTab" :before-leave="beforeLeave">
        <el-tab-pane label="第一步" name="first">
          <el-form-item label="商品分类" prop="categoryId">
            <category-cascader @selected="selectedCategory" :sourceCategoryId.sync="prodForm.categoryId" :isDisabledAll="prodForm.id > 0"></category-cascader>
          </el-form-item>
          <el-form-item label="商品名称" prop="name">
            <el-input v-model="prodForm.name" placeholder="请输入商品名称"></el-input>
          </el-form-item>
          <el-form-item label="品牌" prop="brandId">
            <brand-selection ref="brandSelectionRef" :categoryId="prodForm.categoryId" :sourceBrandId.sync="prodForm.brandId"></brand-selection>
            <el-button type="primary" size="mini" plain @click="brandAssociation"
                       :disabled="prodForm.categoryId === 0">管理品牌关联
            </el-button>
          </el-form-item>
        </el-tab-pane>

        <el-tab-pane label="第二步" name="second">

          <el-form-item label="商品图" prop="albumList">
            <image-upload v-model="prodForm.albumList" :limit=5 :fileSize=120 :img-width="800"
                          :imgHeight="800"></image-upload>
          </el-form-item>

          <el-form-item label="商品详情" prop="describtion">
            <editor v-model="prodForm.describtion" :min-height="192"/>
          </el-form-item>

        </el-tab-pane>

        <el-tab-pane label="第三步" name="third">
          <el-form-item label="sku属性">
            <el-card>
              <el-button type="primary" size="mini" plain @click="handleAddAttribute"><i class="el-icon-plus" style="font-weight: bold"></i>新增属性模块
              </el-button>
              <el-button type="primary" size="mini" plain @click="associationProperties">管理属性关联</el-button>

              <div v-for="index in skuAttributeNum" :key="index">
                <el-form label-width="80px" :rules="skuAttributeRules">
                  <div>
                    <el-form-item label="属性名称" prop="name">
                      <el-select
                        v-model="skuAttribute[index].attributeName"
                        placeholder="请选择"
                        class="propertySelection"
                        clearable
                        filterable
                        :remote-method="queryAttributeList"
                        @change="skuAttributeChanged(index)"
                      >
                        <el-option
                          v-for="attribute in attributeNameOptions"
                          :key="attribute.id"
                          :label="attribute.name"
                          :value="attribute.name"
                          :disabled="attribute.disabled">
                        </el-option>
                      </el-select>
                      <i class="el-icon-delete-solid" style="color:red;cursor: pointer;"
                         @click="handleDeleteAttribute(index)"></i>
                    </el-form-item>

                    <el-form-item label="属性值" prop="value">
                      <el-select
                        v-model="skuAttribute[index].attributeValue"
                        placeholder="请选择"
                        class="propertySelection"
                        clearable
                        multiple
                        filterable
                        :remote-method="queryAttributeValueList(index)"
                        @change="skuAttributeValueChanged(index)"
                      >
                        <el-option
                          v-for="item in skuAttribute[index].attributeValueOptions"
                          :key="item.id"
                          :label="item.value"
                          :value="item.value">
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </div>

                </el-form>
              </div>

            </el-card>
          </el-form-item>

          <el-form-item label="sku信息" v-show="skuCombinations.length > 0">
            <el-card>

                <el-table :data="prodForm.skuList">

                  <el-table-column :label="item" v-for="(item, index) in skuTableHeaders" :key="index" align="center">
                    <template slot-scope="scope">
                      <el-form-item>
                      <span>
                        {{ scope.row.skuCombination[index] }}
                      </span>
                      </el-form-item>
                    </template>
                  </el-table-column>

<!--                  <el-table-column label="状态" align="center" prop="status" >-->
<!--                    <template slot-scope="scope">-->
<!--                      <el-form-item :prop="'skuList.' + scope.$index + '.status'" :rules="skuRules.status">-->
<!--                        <dict-tag :options="dict.type.mall_prod_status" :value="scope.row.status"/>-->
<!--                      </el-form-item>-->
<!--                    </template>-->
<!--                  </el-table-column>-->
                  <el-table-column label="图片" align="center" prop="skuPic">
                    <template v-slot="scope">
                      <el-form-item :prop="'skuList.' + scope.$index + '.skuPic'" :rules="skuRules.skuPic">
                        <image-upload v-model="scope.row.skuPic" :limit=1 :fileSize=120 :img-width="800" :imgHeight="800" :is-show-tip="false"></image-upload>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="供货价" align="center" prop="supplierPrice">
                    <template v-slot="scope">
                      <el-form-item :prop="'skuList.' + scope.$index + '.supplierPrice'" :rules="skuRules.supplierPrice">
                        <el-input v-model="scope.row.supplierPrice" placeholder="请输入"/>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="参考价" align="center" prop="referencePrice">
                    <template v-slot="scope">
                      <el-form-item :prop="'skuList.' + scope.$index + '.referencePrice'" :rules="skuRules.referencePrice">
                        <el-input v-model="scope.row.referencePrice" placeholder="请输入"/>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="销售价" align="center" prop="salePrice">
                    <template v-slot="scope">
                      <el-form-item :prop="'skuList.' + scope.$index + '.salePrice'" :rules="skuRules.salePrice">
                        <el-input v-model="scope.row.salePrice" placeholder="请输入"/>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="sku编码" align="center" prop="skuCode">
                    <template v-slot="scope">
                      <el-form-item :prop="'skuList.' + scope.$index + '.skuCode'" :rules="skuRules.skuCode">
                        <el-input v-model="scope.row.skuCode" placeholder="请输入"/>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="条形码" align="center" prop="barcode">
                    <template v-slot="scope">
                      <el-form-item :prop="'skuList.' + scope.$index + '.barcode'" :rules="skuRules.barcode">
                        <el-input v-model="scope.row.barcode" placeholder="请输入"/>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="毛重" align="center" prop="grossWeight">
                    <template v-slot="scope">
                      <el-form-item :prop="'skuList.' + scope.$index + '.grossWeight'" :rules="skuRules.grossWeight">
                        <el-input v-model="scope.row.grossWeight" placeholder="请输入"/>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="库存" align="center" prop="remained">
                    <template v-slot="scope">
                      <el-form-item :prop="'skuList.' + scope.$index + '.remained'" :rules="skuRules.remained">
                        <el-input v-model="scope.row.remained" placeholder="请输入"/>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="库存变更" align="center" prop="inventoryVariation">
                    <template v-slot="scope">
                      <el-form-item :prop="'skuList.' + scope.$index + '.inventoryVariation'" :rules="skuRules.inventoryVariation">
                        <el-input v-model="scope.row.inventoryVariation" placeholder="请输入"/>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="运费模版id" align="center" prop="freightTemplateId">
                    <template v-slot="scope">
                      <el-form-item :prop="'skuList.' + scope.$index + '.freightTemplateId'" :rules="skuRules.freightTemplateId">
                        <el-select
                          v-model="scope.row.freightTemplateId"
                          clearable
                          placeholder="请选择模版"
                        >
                          <el-option
                            v-for="item in freightTemplateOptions"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="单位" align="center" prop="unit">
                    <template v-slot="scope">
                      <el-form-item :prop="'skuList.' + scope.$index + '.unit'" :rules="skuRules.unit">
                        <el-select
                          v-model="scope.row.unit"
                          filterable
                          clearable
                          remote
                          reserve-keyword
                          placeholder="请输入单位关键字"
                          :remote-method="queryUnitList"
                        >
                          <el-option
                            v-for="item in unitOptions"
                            :key="item.id"
                            :label="item.name"
                            :value="item.name">
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="供应商" align="center" prop="supplierId">
                    <template v-slot="scope">
                      <el-form-item :prop="'skuList.' + scope.$index + '.supplierId'" :rules="skuRules.supplierId">
                        <supplier-selection :sourceSupplierId.sync="scope.row.supplierId"></supplier-selection>
                      </el-form-item>
                    </template>
                  </el-table-column>
                </el-table>

            </el-card>
          </el-form-item>

          <div style="text-align: right; margin-right: 20px" v-show="skuCombinations.length > 0">
            <el-button type="primary" @click="submitNewItems">确 定</el-button>
          </div>
        </el-tab-pane>

      </el-tabs>


      <brand-association ref="associationBrandRef"
                         :categoryId="prodForm.categoryId"
                         @brandAssociationUpdate="brandAssociationUpdate">
      </brand-association>

      <attribute-association ref="attributeAssociationRef" @update="refreshAttribute"></attribute-association>
    </el-form>
  </div>

</template>
<script>
import CategoryCascader from "@/views/components/categoryCascader";
import brandSelection from "@/views/components/brandSelection";
import supplierSelection from "@/views/components/supplierSelection";
import brandAssociation from "@/views/components/brandAssociation";
import attributeAssociation from "@/views/components/attributeAssociation";


import {listAttribute} from "@/api/prod/attribute";
import {calSkuCombination} from "@/utils/sku"
import {addProd, getProd, updateProd} from "@/api/prod/prod";
import {listUnit} from "@/api/prod/unit";
import Brand from "@/views/prod/brand";
import Supplier from "@/views/prod/supplier";
import {listFreightTemplate} from "@/api/prod/freightTemplate";

export default {
  name: "publishProd",
  components: {Supplier, Brand, CategoryCascader, brandAssociation, attributeAssociation,brandSelection, supplierSelection},
  dicts: ['mall_prod_status'],
  props: {},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 发布商品表单参数
      prodForm: {
        id: undefined,
        name: undefined,
        categoryId: undefined,
        brandId: undefined,
        type: 1,   //暂时写死
        status: 0,
        describtion: undefined,
        parameters: [], //暂时写死
        albumList: undefined,
        skuList: [],
      },
      activeName: 'first',

      prodFormRule: {
        name: [
          {required: true, message: "请填写商品名称!", trigger: "blur"},
        ],
        categoryId: [
          {required: true, message: "请选择商品三级分类!", trigger: "blur"},
        ],
        brandId: [
          {required: true, message: "请选择商品品牌!", trigger: "blur"},
        ],

        albumList: [
          {required: true, message: "请上传商品主图!", trigger: "blur"},
        ],
        describtion: [
          {required: true, message: "请填写商品详情!", trigger: "blur"},
        ],
        skuList: [
          {required: true, message: "请填添加sku属性!", trigger: "blur"},
        ],
      },

      skuAttributeRules: {
        name: [
          {required: true, message: "属性名不能为空!", trigger: "blur"},
        ],
        value: [
          {required: true, message: "商品值不能为空!", trigger: "blur"},
        ],
      },

      skuRules: {
        skuPic: [
          {required: true, message: "请上传图片不能为空!", trigger: "blur"},
        ],
        supplierPrice: [
          {required: true, message: "供货价不能为空!", trigger: "blur"},
        ],
        referencePrice: [
          {required: true, message: "参考价不能为空!", trigger: "blur"},
        ],
        salePrice: [
          {required: true, message: "销售价不能为空!", trigger: "blur"},
        ],
        skuCode: [
          {required: true, message: "sku编码不能为空!", trigger: "blur"},
        ],
        barcode: [
          {required: true, message: "条形码不能为空!", trigger: "blur"},
        ],
        grossWeight: [
          {required: true, message: "毛重不能为空!", trigger: "blur"},
        ],
        remained: [
          {required: true, message: "库存不能为空!", trigger: "blur"},
        ],
        inventoryVariation: [
          {required: true, message: "库存变更不能为空!", trigger: "blur"},
        ],
        unit: [
          {required: true, message: "单位不能为空!", trigger: "blur"},
        ],
        status: [
          {required: true, message: "状态不能为空!", trigger: "blur"},
        ],
        freightTemplateId: [
          {required: true, message: "运费模版id不能为空!", trigger: "blur"},
        ],
        supplierId: [
          {required: true, message: "供应商不能为空!", trigger: "blur"}
        ]
      },

      unitOptions: [],
      freightTemplateOptions: [],

      attributeNameOptions: [],
      attributeValueOptionsMap: new Map(),
      skuAttributeNum: 0,
      skuAttribute: [{attributeName: "", attributeValue: []}],
      // 查询参数
      queryAttributeParams: {
        pageNum: 1,
        pageSize: 10,
        categoryId: null,
        needValueList: true,
        name: null
      },
      skuCombinations: [],
      skuTableHeaders: [],
      skuAttributeNames: [],
      skuIdMap: new Map()
    };
  },
  created() {
    this.queryUnitList();
    this.queryFreightTemplateList();
    // const prodId = this.$route.params && this.$route.params.prodId;
    const prodId = this.$route.query && this.$route.query.prodId;
    if (prodId > 0) {
      //编辑商品
      getProd(prodId).then(response =>{

        let prod = response.data;
        let skuList = response.data.skuList;

        //暂时置空 skuList, 避免 sku table 渲染时报错
        prod.skuList = [];
        this.prodForm = prod;

        console.log(skuList)
        console.log(this.prodForm)

        this.loading = false;
        // console.log(JSON.stringify(this.prodForm))

        this.initSkuAttributeForEdit(skuList);

        this.initSkuTableForEdit(skuList);

        //保存一份原始的 sku 属性 与 sku id 的 map 关系, 方便在保存提交前, 维护一下 sku id
        this.saveSkuIdMapping();

      })
    }else{
      this.loading = false;
    }
  },

  methods: {
    handleClickNextTab(tab, event) {

    },
    beforeLeave(goTab, fromTab) {

      if (fromTab === "first" && goTab === "second"){
        if (!this.prodForm.categoryId || !this.prodForm.brandId || !this.prodForm.name) {
          this.$modal.msgWarning("请先完善好第一步信息!");
          return false
        }
      }

      if (fromTab === "second" && goTab === "third"){
        if (!this.prodForm.describtion || !this.prodForm.albumList || this.prodForm.albumList.length === 0) {
          this.$modal.msgWarning("请先完善好第二步信息!");
          return false
        }
      }

      if (fromTab === "first" && goTab === "third"){
        if (!this.prodForm.categoryId || !this.prodForm.brandId || !this.prodForm.name) {
          this.$modal.msgWarning("请先完善好第一步信息!");
          return false
        }

        if (!this.prodForm.describtion || !this.prodForm.albumList || this.prodForm.albumList.length === 0) {
          this.$modal.msgWarning("请先完善好第二步信息!");
          return false
        }
      }

    },
    selectedCategory(level, selectedCategoryId) {
      console.log("父组件中: level = " + level + ", id = " + selectedCategoryId)
      this.prodForm.brandId = null;
    },

    brandAssociation() {
      this.$refs.associationBrandRef.show();
    },
    brandAssociationUpdate() {
      this.$refs.brandSelectionRef.queryBrandList()
    },

    queryUnitList(keywords) {
      let query = {
                    pageNum: 1,
                    pageSize: 50,
                 }

      if (keywords) {
        query.name = keywords;
      }

      listUnit(query).then(response => {
        this.unitOptions = response.rows.map(item => {
          return {
            id: item.id,
            name: item.name
          }
        })
      })
    },

    queryFreightTemplateList() {
      let query = {
                  pageNum: 1,
                  pageSize: 50,
                }

      listFreightTemplate(query).then(response => {
        this.freightTemplateOptions = response.rows.map(item => {
            return {
              id: item.id,
              name: item.name
            }
        })
      })
    },
    handleAddAttribute() {

      let categoryId = this.prodForm.categoryId
      if (!categoryId) {
        this.$modal.msgWarning("请先选择三级类目!");
        return;
      }

      this.skuAttribute.push({attributeName: undefined, attributeValue: []})
      this.skuAttributeNum++
      this.queryAttributeList();
    },
    handleDeleteAttribute(index) {
      this.skuAttributeNum--
      this.skuAttribute.splice(index, 1)
      //重新处理属性选项是否被禁用
      this.handleAttributeOptionDisabled();
      //重新计算 sku 组合
      this.calSkuCombination();
    },
    handleAttributeOptionDisabled() {
      let disabledNames = new Set();
      this.skuAttribute.forEach(e => {
        disabledNames.add(e.attributeName);
      })

      this.attributeNameOptions.forEach(option => {
        option.disabled = disabledNames.has(option.name);
      })
    },
    saveSkuIdMapping(){
      this.prodForm.skuList.forEach(sku =>{
        // console.log(sku.skuCombination);

        //为什么下面要用 sort()
        // let arr1 = ["红色", "12G", "256G"];
        // let arr2 = ["256G", "红色", "12G"];
        // arr1.sort();//['12G', '256G', '红色']
        // arr2.sort();//['12G', '256G', '红色']

        // 用[...sku.skuCombination]避免改变原数组
        this.skuIdMap.set(JSON.stringify([...sku.skuCombination].sort()), sku.id);//方便后续能够根据 属性组合, 找回对应的skuId

        // console.log(sku.skuCombination);

      })
    },
    initSkuTableForEdit(skuList){
      this.getSkuCombination();

      //编辑时, 后台返回的sku缺少 skuCombination 字段, 这里填充一下
      if (skuList){
        for (let i = 0; i < skuList.length; i++) {
          skuList[i].skuCombination = this.skuCombinations[i];
        }
      }
      //维护好 skuCombination 后, 再次赋值给 prodForm, 让其渲染 sku table
      this.prodForm.skuList = skuList;

      //重新计算 sku 组合
      this.calSkuCombination();
    },
    initSkuAttributeForEdit(skuList){
      //初始化一下sku属性选项
      this.queryAttributeList();

      //1.抽取出 所有的 属性名 表头
      //因为每个sku的属性名组合都是一样的, 拿其中一个出来, 抽取属性名到数组即可
      let skuArrList = JSON.parse( skuList[0].skuAttr ); //"[{"颜色": "红色"},{"运存":"8G"},{"内存":"128G"}]"
      let skuAttrNames = [];
      skuArrList.forEach(item => { //{\"颜色\":\"红色\"}
        let skuArrName = Object.keys(item)[0];
        skuAttrNames.push(skuArrName);
      })
      //this.skuTableHeaders = skuAttrNames;

      this.skuAttributeNum = skuAttrNames.length;

      //2.循环 sku 属性名称, 生成 skuAttribute
      for (let i = 0; i < skuAttrNames.length; i++) {
        let skuAttrName = skuAttrNames[i];

        let attribute = {};
        attribute.attributeName = skuAttrName;
        attribute.attributeValue = [];

        // {
        //   "id": 4,
        //   "skuAttr": "[{"颜色": "红色"},{"运存":"8G"},{"内存":"128G"}]"
        // },
        // {
        //   "id": 5,
        //   "skuAttr": "[{"颜色": "绿色"},{"运存":"12G"},{"内存":"128G"}]"
        // }
        skuList.forEach(sku =>{
          let skuArrList = JSON.parse( sku.skuAttr );
          let attr = skuArrList[i]; // 利用数据 sku.skuAttr 和 skuAttrNames 有索引对应的规律
          let skuAttrValue = Object.values(attr)[0];
          if (attribute.attributeValue.indexOf(skuAttrValue) === -1){
            attribute.attributeValue.push(skuAttrValue);
          }
        })

        this.skuAttribute.push(attribute); // {attributeName: "", attributeValue: []}
      }

    },
    queryAttributeValueList(index) {
      let attributeName = this.skuAttribute[index].attributeName;
      this.skuAttribute[index].attributeValueOptions = this.attributeValueOptionsMap.get(attributeName);
    },
    queryAttributeList(keywords) {
      this.queryAttributeParams.name = keywords;

      if (!keywords) {
        this.queryAttributeParams.name = ""
      }

      let categoryId = this.prodForm.categoryId
      if (!categoryId) {
        this.$modal.msgWarning("请先选择三级类目!");
        return;
      }

      this.queryAttributeParams.categoryId = categoryId;
      listAttribute(this.queryAttributeParams).then(response => {
        let attributeList = response.rows;

        this.attributeNameOptions = attributeList.map(item => {

          //先保存属性值选项到 属性值选项的 map 中
          let attributeValueOptions = item.attributeValueList.map(attributeValue => {
            return {
              id: attributeValue.id,
              value: attributeValue.value
            }
          });
          //                                属性名name  对应的属性值选项
          this.attributeValueOptionsMap.set(item.name, attributeValueOptions);

          //是否在其他组的选框选中了
          let disabled = this.skuAttribute.some(e => e.attributeName === item.name);
          //返回属性名选项
          return {
            id: item.id,
            name: item.name,
            disabled: disabled
          }
        })
      });
    },
    skuAttributeChanged(index) {
      // let attributeName = this.skuAttribute[index].attributeName;

      //设置已选属性名称为 禁用
      this.handleAttributeOptionDisabled();
      //重新计算 sku 组合
      this.calSkuCombination();
    },
    skuAttributeValueChanged(index) {
      //重新计算 sku 组合
      this.calSkuCombination();
    },
    getSkuCombination(){
      let totalProps = [];
      this.skuAttributeNames = [];
      this.skuAttribute.forEach(item => {
        if (item.attributeName && item.attributeValue && item.attributeValue.length > 0) {
          totalProps.push(item.attributeValue);
          this.skuAttributeNames.push(item.attributeName);
        }
      })
      this.skuCombinations = calSkuCombination(totalProps);
      // console.log(this.skuCombinations)
    },
    synchronizeSkuCombination(){
      for (let i = 0; i < this.prodForm.skuList.length; i++) {
        //只需循环更新一下每个sku的 skuCombination 即可
        this.prodForm.skuList[i].skuCombination = this.skuCombinations[i];
      }
    },
    calSkuCombination() {
      this.getSkuCombination();
      //动态构造 sku 条目
      if (this.skuCombinations.length === 0) {
        this.prodForm.skuList = [];
      } else if(this.prodForm.skuList.length === this.skuCombinations.length){
        //skuList里的条数 和 最新的 sku组合 条数一样时
        this.synchronizeSkuCombination();
      }else if(this.prodForm.skuList.length > this.skuCombinations.length) {
        //skuList里的条数 大于 最新的 sku组合的条数时(用户移走了一些sku属性)
        //先剪掉skuList里多出来的 sku
        // this.prodForm.skuList = this.prodForm.skuList.slice(0, this.skuCombinations.length);
        this.prodForm.skuList = this.prodForm.skuList.filter(sku => {
          return this.skuCombinations.some(skuCombination => JSON.stringify(skuCombination) === JSON.stringify(sku.skuCombination));
        })

        //skuList里的条数 和 最新的 sku组合 条数一样时
        //this.synchronizeSkuCombination();
      } else {
        //skuList里的条数 小于 最新的 sku组合的条数时(用户加了一些sku属性)
        //组装 n 条新的sku
        this.skuCombinations.forEach(skuCombination => {
          // console.log(skuCombination)
          if ( !this.prodForm.skuList.some(item => JSON.stringify(item.skuCombination) === JSON.stringify(skuCombination) )){
            let sku = this.buildNewSkuObj();
            sku.skuCombination = skuCombination
            this.prodForm.skuList.push(sku);
          }
        })
      }

      //sku 属性做成 动态表头
      this.skuTableHeaders = this.skuAttributeNames;
    },
    buildNewSkuObj(){
      let sku = {};
      sku.skuPic = undefined;
      sku.skuName = "";
      sku.supplierPrice = 0;
      sku.referencePrice = 0;
      sku.salePrice = 0;
      sku.skuCode = "";
      sku.barcode = "";
      sku.grossWeight = 0;
      sku.remained = 0;
      sku.status = 0;
      sku.inventoryVariation = 0;
      sku.freightTemplateId = 0;
      sku.unit = "";
      sku.supplierId = null;
      return sku;
    },
    processSkuList() {
      if (this.prodForm.skuList.length === 0) {
        return;
      }

      this.prodForm.skuList = this.prodForm.skuList.map(sku => {
        let skuAttr = [];
        for (let i = 0; i < this.skuTableHeaders.length; i++) {
          let info = {};
          let attributeName = this.skuTableHeaders[i];
          let attributeValue = sku.skuCombination[i];
          info[attributeName] = attributeValue;
          skuAttr.push(info);
        }
        // sku.skuAttr = skuAttr;
        sku.skuAttr = JSON.stringify(skuAttr);
        return sku;
      })
    },
    associationProperties() {
      let categoryId = this.prodForm.categoryId
      this.$refs.attributeAssociationRef.show(categoryId);
    },
    refreshAttribute() {
      this.queryAttributeList()
    },

    submitNewItems() {

      this.$refs.prodFormRef.validate(validProd => {
        if (!validProd){
          this.$modal.msgWarning("请先完善sku必填信息!");
          return;
        }

        if (typeof(this.prodForm.albumList) == 'string' ){
          this.prodForm.albumList = this.prodForm.albumList.split(",");
        }

        this.processSkuList();
        this.prodForm.parameters = JSON.stringify(this.prodForm.parameters)

        console.log(JSON.stringify(this.prodForm))

        if (this.prodForm.id){

          //维护一下 sku id (可能用户在编辑商品时, 删除了某条sku, 后面又添加回来)
          this.prodForm.skuList.forEach(sku =>{
            if (!sku.id){
              // 用[...sku.skuCombination]避免改变原数组
              let skuId = this.skuIdMap.get(JSON.stringify([...sku.skuCombination].sort()));
              if (skuId){
                sku.id = skuId;
              }
            }
          })

          updateProd(this.prodForm).then(response => {
            this.$modal.msgSuccess("修改成功");
            // this.$router.push("/prod/prod");
            this.$router.push({ path: "/prod/prod", query: { t: new Date().getTime() + "" } });
          })
        }else {
          addProd(this.prodForm).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.$router.push({ path: "/prod/prod", query: { t: new Date().getTime() + "" } });
          })
        }

      })
    }
  },
};
</script>

<style>
.el-form-item {
  margin-top: 20px;
}

.brandDropdownButton {
  margin-right: 5px
}

.propertySelection {
  width: 70%;
  margin-right: 5px
}


.el-upload--picture-card {
  border: 1px dashed #13C3C7;
}

.el-upload--picture-card:hover {
  border-color: #13C3C7;
  color: #13C3C7;
}

.el-upload--picture-card {
  width: 50px;
  height: 50px;
  font-size: 8px !important;
}

.el-upload {
  width: 50px;
  height: 50px;
  line-height: 50px;
  font-size: 8px;
}

.el-upload-list--picture-card .el-upload-list__item {
  width: 50px;
  height: 50px;
  line-height: 50px;
  font-size: 8px;
}

.el-upload--picture-card i {
  font-size: 14px;
}

.el-upload-list--picture-card .el-upload-list__item-status-label {
  width: 0px;
}

.el-upload-list--picture-card .el-upload-list__item-actions:hover {
  opacity: 1;
  font-size: 8px;
}

.el-upload-list--picture-card .el-upload-list__item-thumbnail {
  width: 50px;
  height: 50px;
  line-height: 50px;
  font-size: 8px;
}

.avatar {
  width: 50px;
  height: 50px;
}
</style>
